<?php

/*
Plugin Name: Docunext Cache
Plugin URI: 
Description: Caching thanks to Cache Lite
Version: 0.1
Author: Albert Lash
Author URI: http://www.docunext.com
*/

/*
*
*       DOCUNEXT CACHE
*
*       Copyright 2006 Albert Lash / Savonix  (http://www.savonix.com)
* 		License: LGPL http://www.gnu.org/licenses/lgpl.html
*
*/


/* 

Ideas: 
1. Make sure varied placement of footer call doesn't break anything. Search for closing tags in output?
2. Ability to store cache in various places - try to find a writeable folder. 
3. Ability to store to different backends - file, xcache, where else? 
4. Test with other plugins. 
5. How to manage lifetime? Is it necessary?
6. Turn off caching for people who are logged in. 


Find potential directory targets: 

find -maxdepth 3 -name proc -prune -o -noleaf -user www-data -type d

if there is no directory, just use memory?

*/





$global_cache_dir = "/tmp/";

function check_cache() { 

		

	global $global_cache_dir;
	
	require_once('Cache/Lite.php');

	$my_domain_name = $_SERVER['HTTP_HOST'];
	$cache_dir = $global_cache_dir.$my_domain_name."/";
	if(!is_dir($cache_dir)) { 
		mkdir($cache_dir,0700);
	}
	$options = array('cacheDir'=>$cache_dir,'caching'  => 1,'lifeTime' => '86400');
	$cache = new Cache_Lite($options);

	// For now simply purge all caches if there is a post.
	if(!empty($_POST)) {                     
	       	$cache->clean();
		return;
	}

	$my_request_uri = $_SERVER['REQUEST_URI'];
	$my_user_id  = 1;
	$user = wp_get_current_user();
	if ( $user->ID ) {
		$my_user_id = $user->ID;
	}
	// why testing for bot here?
	if(stripos($agent,"google") || stripos($agent,"slurp") || stripos($agent,"msnbot") || stripos($agent,"spider") || stripos($agent,"bot")) {
		$bot="yes";
	}
	
	// why was this only caching for bots?
  if($output = $cache->get($my_request_uri, $my_user_id, FALSE)) {

        // Check file mtime, and potentially return 304 response code.
        // Only for testing and production sites.
        $mynid = $cache_dir.'cache_'.md5($my_user_id).'_'.md5($my_request_uri);
        $last_modified_str = filemtime($mynid);
        $file_size = filesize($mynid);
        $etag = md5($last_modified_str);
        $last_modified = gmdate('D, d M Y H:i:s', $last_modified_str);

        $request = getallheaders();
        if (isset($request['If-Modified-Since'])) {
           $modifiedSince = explode(';', $request['If-Modified-Since']);
           $modifiedSince = strtotime($modifiedSince[0]);
        } else {
           $modifiedSince = 123;
        }
        // Client cache! Only on for...
        if ($last_modified_str <= $modifiedSince && $modifiedSince!=123) {
		while (@ob_end_clean());
                header("HTTP/1.0 304 Not Modified");
                exit();
        }
	while (@ob_end_clean());
	ob_start();
	header("Last-Modified: " . $last_modified . " GMT");
	// Client cache doesn't exist, but server does
        if( eregi("deflate",$_SERVER['HTTP_ACCEPT_ENCODING'])){
                header("Content-Encoding: deflate");
                echo $output;
        } else {
		$output = gzinflate($output);
	        echo $output;
        }
	header("Content-Length: ".ob_get_length());
	ob_flush();
	while (@ob_end_clean());
	exit;

  } else {
	// No problem, we'll create the page again, and cache the contents in the shutdown function.
	ob_start();
  }




}

function save_new_cache() {

	if(!empty($_POST)) {
        	return;
	}
	require_once('Cache/Lite.php');
	
	global $global_cache_dir;
		
	$my_domain_name = $_SERVER['HTTP_HOST'];
	$cache_dir = $global_cache_dir.$my_domain_name."/";	
	$options = array('cacheDir'=>$cache_dir,'caching'  => 1,'lifeTime' => '86400');
	$cache = new Cache_Lite($options);

	$my_request_uri = $_SERVER['REQUEST_URI'];
	$my_user_id  = 1;
	$output = ob_get_contents();
	while (@ob_end_clean());
	$right_now = date("D M j G:i:s T Y");
	$tag = TRUE;

	$output .= "</body></html>";
	
	$request = getallheaders();
	// Since there is no cache, we'll assume that it was modified very recently, essentially now.
	header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
	if( eregi("deflate",$_SERVER['HTTP_ACCEPT_ENCODING']) ){
		if($tag === TRUE) { 
			$output .= "\n<!-- This content cached by the Docunext Cache at $right_now. -->";		
		}
	 	$output = gzdeflate($output,9);
		header("Content-Encoding: deflate");
		ob_start();
		echo $output; 
		$user = wp_get_current_user();
		if ( $user->ID ) {
			$my_user_id = $user->ID;
		}
		$cache->save($output, $my_request_uri, $my_user_id);
	} else { 
		ob_start();
		echo $output;

	}
	header("Content-Length: ".ob_get_length());
	ob_end_flush();
        exit;
	


}

// Microsoft IE is lame and can't handle adsense and caching at the same time.
if(!strpos($_SERVER['HTTP_USER_AGENT'],'MSIE')) {
	add_action('init', 'check_cache');

	add_action('wp_footer', 'save_new_cache');
//add_action('shutdown', 'save_new_cache');
}
?>
